#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <poll.h>
#include <string.h>
#include <time.h>
#include <errno.h>

#include "ae.h"
#include "zmalloc.h"
#include "ae_epoll.c"

/* 初始化创建EventLoop, 注意错误的处理逻辑和掩码的初始化 */
aeEventLoop *aeCreateEventLoop(int setsize) {
    aeEventLoop *eventLoop;
    int i;
    if ((eventLoop = zmalloc(sizeof(*eventLoop)) == NULL)) goto err;
    eventLoop->events = zmalloc(sizeof(aeFileEvent) * setsize);
    eventLoop->fired = zmalloc(sizeof(aeFiredEvent) * setsize);
    if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err;
    eventLoop->setsize = setsize;
    eventLoop->lastTime = time(NULL);
    eventLoop->timeEventHead = NULL;
    eventLoop->timeEventNextId = 0;
    eventLoop->stop = 0;
    eventLoop->maxfd = -1;
    eventLoop->beforesleep = NULL;
    if (aeApiCreate(eventLoop) == -1) goto err;

    for (i = 0; i < setsize; i++)
        eventLoop->events[i].mask = AE_NONE;
    return eventLoop;
err:
    if (eventLoop) {
        zfree(eventLoop->events);
        zfree(eventLoop->fired);
        zfree(eventLoop);
    }
    return NULL;
}

/* 返回setsize的大小 */
int aeGetSetSize(aeEventLoop *eventLoop) {
    return eventLoop->setsize;
}

/* 重新设置setsize, 需要考虑如下的几种情况:
 1. maxfd和setsize关系, setsize和之前setsize关系
 2. 采用zrealloc重新分配内存, 当然包括底层的内存
 3. 新增的部分需要初始化AE_NONE
*/
int aeResizeSetSize(aeEventLoop *eventLoop, int setsize) {
    int i;
    if (setsize == eventLoop->setsize) return AE_OK;
    if (eventLoop->maxfd >= setsize) return AE_ERR;
    if (aeApiResize(eventLoop, setsize) == -1) return AE_ERR;
    eventLoop->events = zrealloc(eventLoop->events, sizeof(aeFileEvent) * setsize);
    eventLoop->fired = zrealloc(eventLoop->fired, sizeof(aeFiredEvent) * setsize);
    eventLoop->setsize;
    for (i = eventLoop->maxfd + 1; i < setsize; i++)
        eventLoop->events[i].mask = AE_NONE;
    return AE_OK;
}

/* 删除EventLoop:
  1. 删除底层数据
  2. FileEvent
  3. FiredEvent
  4. EventLoop本身
*/
void aeDeleteEventLoop(aeEventLoop *eventLoop) {
    aeApiFree(eventLoop);
    zfree(eventLoop->events);
    zfree(eventLoop->fired);
    zfree(eventLoop);
}

/* 停止EventLoop */
void aeStop(aeEventLoop *aeEventLoop) {
    aeEventLoop->stop = 1;
}

/* 创建文件事件:
  1. 文件fd是否已经大于setsize
  2. 底层API创建事件
  3. 判断读写事件设置proc
  4. 放置clientData
  5. 判断maxfd
 */
int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, aeFileProc *proc, void *clientData) {
    if (fd >= eventLoop->setsize) {
        errno = ERANGE;
        return AE_ERR;
    }
    aeFileEvent *fe = &eventLoop->events[fd];
    if (aeApiAddEvent(eventLoop, fd, mask) == -1)
        return AE_ERR;
    fe->mask |= mask;
    if (mask & AE_READABLE) fe->rfileProc = proc;
    if (mask & AE_WRITABLE) fe->wfileProc = proc;
    fe->clientData = clientData;
    if (fd > eventLoop->maxfd)
        eventLoop->maxfd = fd;
    return AE_OK;
}

/* 删除文件事件:
  1. 首先判断是否越界
  2. 删除对应的掩码
  3. 根据掩码判断是否要重置maxfd
  4. 底层删除event对应的掩码
 */
void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask) {
    if (fd >= eventLoop->setsize) {
        errno = ERANGE;
        return;
    }
    aeFileEvent *fe = eventLoop->events + fd;
    if (fe->mask = AE_NONE) return;
    fe->mask &= (~mask);
    if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
        int j;
        for (j = eventLoop->maxfd - 1; j >= 0; j--)
            if (eventLoop->events[j].mask != AE_NONE) break;
        eventLoop->maxfd = j;
    }
    aeApiDelEvent(eventLoop, fd, mask);
}


/* 获得事件的掩码 */
int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
    if (fd >= eventLoop->setsize) return 0;
    aeFileEvent *fe = &eventLoop->events[fd];
    return fe->mask;
}

/* 获取当前时间 */
static void aeGetTime(long *seconds, long *milliseconds) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    *seconds = tv.tv_sec;
    *milliseconds = tv.tv_usec / 1000;
}

static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {
    long cur_sec, cur_ms, when_sec, when_ms;
    aeGetTime(&cur_sec, &cur_ms);
    when_ms = cur_ms + milliseconds;
    when_sec = cur_sec + when_ms / 1000;
    when_ms = when_ms % 1000;
    *sec = when_sec;
    *ms = when_ms;
}


/* 创建时间事件, 采用头插法:
  1. 创建时间事件
  2. 采用头插法插入到时间事件链表
*/
long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, aeTimeProc *proc, void *clientData, aeEventFinalizerProc *finalizerProc) {
    long long id = eventLoop->timeEventNextId++;
    aeTimeEvent *te;
    te = zmalloc(sizeof(*te));
    if (te == NULL) return AE_ERR;
    te->id = id;
    aeAddMillisecondsToNow(milliseconds, &te->when_sec, &te->when_ms);
    te->timeProc = proc;
    te->finalizerProc = finalizerProc;
    te->clientData = clientData;
    te->next = eventLoop->timeEventHead;
    eventLoop->timeEventHead = te;
    return id;
}

/* 删除指定id的时间事件:
 1. 遍历链表找到对应的时间事件
 2. 注意头部的问题
 3. 进行正常的链表节点删除操作
 */
int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id) {
    aeTimeEvent *te, *prev = NULL;
    te = eventLoop->timeEventHead;
    while (te) {
        if (te->id == id) {
            if (prev == NULL) 
                eventLoop->timeEventHead = te->next;
            else
                prev->next = te->next;
            
            if (te->finalizerProc)
                te->finalizerProc(eventLoop, te->clientData);
            zfree(te);
            return AE_OK;
        }
        prev = te;
        te = te->next;
    }
    return AE_ERR;
}

/* 寻找时间最近的定时器, 采用简单的遍历方式即可:
    可用的优化方式: 按序插入或者使用跳表
*/
static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop) {
    aeTimeEvent *nearest = NULL;
    aeTimeEvent *te = eventLoop->timeEventHead;
    while (te) {
        if (!nearest || te->when_sec < nearest->when_sec || 
            (te->when_sec == nearest->when_sec && te->when_ms < nearest->when_ms))
            nearest = te;
        te = te->next;
    }
    return nearest;
}

/* 处理时间事件:
 1. 获取当前时间, 对比之后判断是否发生时钟移动, 如果发生则尽早处理所有任务
 2. 采用判断时间的方式决定是否处理时间事件, 如果可以, 直接处理, 通过返回值判断是否需要额外处理
*/
static int processTimeEvents(aeEventLoop *eventLoop) {
    int processed = 0;
    aeTimeEvent *te;
    long long maxId;
    time_t now = time(NULL);

    /* 发生时钟移动: 采用尽早完成任务方式解决 */
    if (now < eventLoop->lastTime) {
        te = eventLoop->timeEventHead;
        while (te) {
            te->when_sec = 0;
            te = te->next;
        }
    }
    eventLoop->lastTime = now;
    te = eventLoop->timeEventHead;
    maxId = eventLoop->timeEventNextId - 1;
    while (te) {
        long now_sec, now_ms;
        long long id;
        if (te->id > maxId) {
            te = te->next;
            continue;
        }
        aeGetTime(&now_sec, &now_ms);
        if (now_sec > te->when_sec || 
            (now_sec == te->when_sec && now_ms >= te->when_ms)) {
            int retval;
            id = te->id;
            retval = te->timeProc(eventLoop, id, te->clientData);
            processed++;
            if (retval != AE_NOMORE) 
                aeAddMillisecondsToNow(retval, &te->when_sec, &te->when_ms);
            else
                aeDeleteTimeEvent(eventLoop, id);
        } else {
            te = te->next;
        }
    }
    return processed;
}

/* 处理事件, 但是需要考虑不同flags对应的操作:
 * AE_ALL_EVENTS表示处理所有的事件
 * AE_FILE_EVENTS表示处理文件事件
 * AE_TIME_EVENTS表示处理时间事件
 * AE_DONT_WAIT处理所有事件
 * 因此处理流程如下:
 *  1. 没有任何FLAG直接退出
 *  2. 如果有需要处理时间事件(并且非DONT_WAIT):
 *      * 首先计算距离最近时间事件的时间
 *      * 采用poll进行休眠对应的时间
 *      * 那么如果是DONT_WAIT则设置间隔为0, 否则BLOCK
 *  3. 采用aeApiPoll处理底层IO事件
 *  4. 每一个fired就是处理好的事件, 根据mask调用对应的处理程序(这里需要double check, 因为存在remove的情况)
 *  5. 最后处理时间事件
*/
int aeProcessEvents(aeEventLoop *eventLoop, int flags) {
    int processed = 0, numevents;
    if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;

    if (eventLoop->maxfd != -1 || ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
        int j;
        aeTimeEvent *shortest = NULL;
        struct timeval tv, *tvp;
        if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) 
            shortest = aeSearchNearestTimer(eventLoop);
        if (shortest) {
            long now_sec, now_ms;
            aeGetTime(&now_sec, now_ms);
            tvp = &tv;
            tvp->tv_sec = shortest->when_sec = now_sec;
            if (shortest->when_ms < now_ms) {
                tvp->tv_usec = ((shortest->when_ms + 1000) - now_ms) * 1000;
                tvp->tv_sec --;
            } else {
                tvp->tv_usec = (shortest->when_ms - now_ms) * 1000;
            }
            if (tvp->tv_sec < 0) tvp->tv_sec = 0;
            if (tvp->tv_usec < 0) tvp->tv_usec = 0;
        } else {
            if (flags & AE_DONT_WAIT) {
                tv.tv_sec = tv.tv_usec = 0;
                tvp = &tv;
            } else {
                tvp = NULL;
            }
        }

        numevents = aeApiPoll(eventLoop, tvp);
        for (j = 0; j < numevents; j++) {
            int mask = eventLoop->fired[j].mask;
            int fd = eventLoop->fired[j].fd;
            int rfired = 0;
            aeFileEvent *fe = eventLoop->events + fd;

            if (fe->mask & mask & AE_READABLE) {
                rfired = 1;
                fe->rfileProc(eventLoop, fd, fe->clientData, mask);
            }
            if (fe->mask & mask & AE_WRITABLE) {
                if (!rfired || fe->wfileProc != fe->rfileProc)
                    fe->wfileProc(eventLoop, fd, fe->clientData, mask);
            }
            processed++;
        }
    }
    if (flags & AE_TIME_EVENTS)
        processed += processTimeEvents(eventLoop);
    return processed;
}

/* 等待对应的时间知道fd准备好:
    1. 这里用的是POLL的API函数, 本质上需要对POLL进行操作
    2. 采用POLL作为定时函数, 根据是否准备好进行操作
*/
int aeWait(int fd, int mask, long long milliseconds) {
    struct pollfd pfd;
    int retmask = 0, retval;
    memset(&pfd, 0, sizeof(pfd));
    pfd.fd = fd;
    if (mask & AE_READABLE) pfd.events |= POLLIN;
    if (mask & AE_WRITABLE) pfd.events |= POLLOUT;
    if ((retval = poll(&pfd, 1, milliseconds)) == 1) {
        if (pfd.revents & POLLIN) retmask |= AE_READABLE;
        if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE;
        if (pfd.revents & POLLERR) retmask |= AE_WRITABLE;
        if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE;
        return retmask;
    } else {
        return retval;
    }
}

/* 主事件循环, 在此进行对应的操作:
    1. 在每次休眠之前执行对应的休眠程序
    2. 处理事件
*/
void aeMain(aeEventLoop *eventLoop) {
    eventLoop->stop = 0;
    while (!eventLoop->stop) {
        if (eventLoop->beforesleep != NULL)
            eventLoop->beforesleep(eventLoop);
        aeProcessEvents(eventLoop, AE_ALL_EVENTS);
    }
}

/* 返回函数的API名称 */
char *aeGetApiName(void) {
    return aeApiName();
}

/* 设置休眠程序 */
void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) {
    eventLoop->beforesleep = beforesleep;
}